<template>
    <el-container v-loading="loading">
        <el-aside style="width: 18%;height: 100%; margin-top: 0.5%;">
            <el-collapse>
                <el-collapse-item title="公共模型">
                    <el-container>
                        <el-main class="modelsContainer"
                                 style="height:100%;width:100%;float: left; top:20px; left:10px; border:2px solid black;">
                            <el-row>
                                <el-col :span="12" v-for="(item, index) in models" :key="index">
                                    <el-card :body-style="{ padding: '0px' }" style="margin:10px 12.5%;"
                                             :id="item.artifactId">
                                        <img :src="'http://192.168.1.5:9500/dbfg/'+item.picPath"
                                             style="text-align: center; width: 60px;height: 35px; margin-left: 22px;margin-top: 10px"
                                             class="image">
                                        <div style="padding: 4px;">
                                            <label style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"
                                                   :title="item.name">{{item.name}}</label>
                                        </div>
                                    </el-card>
                                </el-col>
                            </el-row>
                            <!--<el-row class="model" v-for="(item, index) in models" :key=index :id="item.artifactId">-->
                            <!--{{item.name}}-->
                            <!--</el-row>-->
                        </el-main>
                        <!--<el-footer style="background-color: red;height: 50px">-->
                        <!--<el-pagination>-->
                        <!--</el-pagination>-->
                        <!--</el-footer>-->
                    </el-container>
                </el-collapse-item>
                <el-collapse-item title="工具箱">
                    <el-container style="border:2px solid black;">
                        <el-main style="min-height: 280px">
                            <div class="modelsContainer"
                                 style="height:100%;width:100%;float: left; top:20px; left:10px; ">
                                <el-row>
                                    <el-col :span="24" v-for="(item, index) in workflows" :key="index">
                                        <el-card :body-style="{ padding: '0px' }" style="margin:2px 2%;"
                                                 :id="item.id">
                                            <div style="padding: 2px;">
                                                <label style="padding-right: 6px;margin-left: 10px">{{item.name}}</label>
                                                <!--<label>{{item.lastmodifytime}}</label>-->
                                                <i class="el-icon-info" @click="dragInfo(item.id)"
                                                   style="float: right;margin:4px;"></i>
                                                <i class="el-icon-circle-plus" @click="dragAdd(item.id)"
                                                   style="float: right;margin: 4px;"></i>
                                                <i class="el-icon-remove" @click="dragDelete(item.id)"
                                                   style="float: right;margin: 4px;"></i>
                                            </div>
                                        </el-card>
                                    </el-col>
                                </el-row>
                                <!--<el-row class="model" v-for="(item, index) in models" :key=index :id="item.artifactId">-->
                                <!--{{item.name}}-->
                                <!--</el-row>-->
                            </div>
                        </el-main>
                        <el-footer style="padding: 0;height: 30px">
                            <el-pagination
                                    @size-change="handleSizeChange1"
                                    @current-change="handleCurrentChange1"
                                    :page-size="pageSize1"
                                    :current-page="pageNo1"
                                    layout="prev,pager,next"
                                    :total="totalCount1"
                                    style="text-align: center">
                            </el-pagination>
                        </el-footer>
                    </el-container>
                </el-collapse-item>
            </el-collapse>
        </el-aside>
        <el-container>
            <el-main style="padding: 0;">
                <div style="float:right;margin-right: 15px">
                    <!--<el-button type="primary" @click="loadFlow">加载</el-button>-->

                    <el-button type="primary" @click="saveFlow">保存</el-button>
                    <el-button type="primary" @click="runFlow">运行</el-button>
                    <el-button type="primary" @click="cleanFlow">清空</el-button>
                    <!--<el-button type="primary" @click="wuhuan">验证</el-button>-->
                </div>
                <div id="workFlowContainer" style="height: 90%">
                    <!--双击节点-删除-->
                </div>
                <paramInputDialog></paramInputDialog>
                <drag-info-dialog></drag-info-dialog>
                <new-workflow-dialog></new-workflow-dialog>
                <save-workflow-dialog @getNewWorkFlowId="getNewWorkFlowId"></save-workflow-dialog>
            </el-main>
        </el-container>
    </el-container>
</template>

<script>
    import jsplumb from "jsplumb";
    import paramInputDialog from '../toolbox/ParamInputDialog';
    import dragInfoDialog from '../toolbox/dragInfoDialog'
    import newWorkflowDialog from "../toolbox/newWorkflowDialog"
    import saveWorkflowDialog from "../toolbox/saveWorkflowDialog"
    import {generateUUID,MathRand} from "../../util/util"

    export default {
        name: "workFlow",
        data() {
            return {
                innited: 0,
                loading: false,
                totalCount: 0,
                pageSize: 10,
                pageNo: 1,
                jsPlumbInstance: {},
                models: [],
                workflows: [],
                currentWorkflowId: "",
                // currentWorkflowName: "",
                modelsInFlow: [],//{id:"",modelId:"",param:[]}
                // modelNodesNumb: 0,
                tableData: [],
                pageSize1: 8,
                pageNo1: 1,
                totalCount1: 0
            };
        },
        components: {
            paramInputDialog,
            dragInfoDialog,
            newWorkflowDialog,
            saveWorkflowDialog
        },
        computed: {
            picPath() {
                // if(this.item.picPath!==''){
                return 'http://192.168.1.5:9500/dbfg/' + this.item.picPath
                // }else{
                //     return '../../../static/img/loginHeader.jpg'
                // }
            },
            getName(name) {
                if (name.length > 10) {
                    return name.substring(0, 10)
                }
            }
        },
        watch: {},
        methods: {
            //有向无环图验证
            wuhuan() {
                let result = false;
                let conn_list = this.jsPlumbInstance.getAllConnections();
                let edges = [];
                for (let i = 0; i < conn_list.length; i++) {
                    let source_id = conn_list[i]["sourceId"];
                    let target_id = conn_list[i]["targetId"];
                    let conn = {
                        "source": source_id,
                        "target": target_id
                    };
                    edges.push(conn);
                }
                const nodes = [];
                const list = {}; // 邻接表
                const queue = []; // 入度为0的节点集合
                const indegree = {};
                edges.forEach(e => {
                    const {source, target} = e;
                    if (!nodes.includes(source)) {
                        nodes.push(source);
                    }
                    if (!nodes.includes(target)) {
                        nodes.push(target);
                    }
                    addEdge(source, target);
                });
                const V = nodes.length;

                nodes.forEach(node => {
                    if (!indegree[node]) indegree[node] = 0;
                    if (!list[node]) list[node] = [];
                });

                function addEdge(source, target) {
                    if (!list[source]) list[source] = [];
                    if (!indegree[target]) indegree[target] = 0;
                    list[source].push(target);
                    indegree[target] += 1;
                }

                // function sort() {
                Object.keys(indegree).forEach(id => {
                    if (indegree[id] === 0) {
                        queue.push(id);
                    }
                });
                let count = 0;
                while (queue.length) {
                    ++count;
                    const currentNode = queue.pop();
                    const nodeTargets = list[currentNode];
                    for (let i = 0; i < nodeTargets.length; i++) {
                        const target = nodeTargets[i];
                        indegree[target] -= 1;
                        if (indegree[target] === 0) {
                            queue.push(target);
                        }
                    }
                }
                // false 没有输出全部顶点，有向图中有回路
                result = count < V;
                // }
                // alert(result);
                return !result;
            },
            handleSizeChange1(val) {
                this.pageSize1 = val;
                this.getWorkflow();
            },
            handleCurrentChange1(val) {
                this.pageNo1 = val;
                this.getWorkflow();
            },
            dragDelete(id) {
                let that = this;
                this.$confirm('是否删除该任务？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let url = "http://192.168.1.5:9500/dbfg/workflow/dags/delete/" + id;
                    this.$axios.delete1(url).then(res => {
                        if (res.code === 200) {
                            that.$message({
                                message: res.message,
                                type: 'success'
                            });
                            that.getWorkflow();
                        } else {
                            that.$message({
                                type: 'warning',
                                message: res.message
                            })
                        }
                    }).catch(function (error) {
                        console.log(error);
                        that.$message.error('删除工作流失败！')
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            dragInfo(id) {
                this.$Bus.$emit("dragInfo", id);
            },
            dragAdd(id) {
                this.cleanFlow();
                // $("#workFlowContainer").empty();
                let url = "http://192.168.1.5:9500/dbfg/workflow/dags/load/" + id;
                this.$axios.get(url).then(res => {
                    if (res.code == 200) {
                        let style = JSON.parse(res.body.style);
                        let nets = style.net;
                        let nets_conn = style.connections;
                        let mynodes = JSON.parse(res.body.nodes);
                        this.modelsInFlow = mynodes;
                        // this.modelNodesNumb = mynodes.length;
                        let that = this;
                        this.currentWorkflowId = res.body.id;
                        // this.currentWorkflowName = res.body.name;
                        //画节点及其事件注册
                        jQuery.each(nets, function (id, val) {
                            that.jsPlumbInstance.ready(function () {
                                let nodeHtml = '';
                                let paramBtnId = val['id'] + "_param";
                                nodeHtml = `<div id="${val['id']}" class="modelNode"><span>${val['name']}<i class="fa fa-wpforms" id="${paramBtnId}"></i></span></div>`;
                                $("#workFlowContainer").append(nodeHtml);
                                $("#" + val['id']).css({
                                    // 'left': parseInt(val['left'].split('px')) + $("#workFlowContainer").offset().left,
                                    // 'top': parseInt(val['top'].split('px')) + $("#workFlowContainer").offset().top
                                    'left': parseInt(val['left'].split('px')),
                                    'top': parseInt(val['top'].split('px'))
                                });
                                if (document.getElementById(paramBtnId)) {
                                    document.getElementById(paramBtnId).onclick = function () {
                                        // alert("点击事件")
                                        let modelId = val['id'].substring(0, val['id'].indexOf("_"));
                                        let url = "http://192.168.1.5:9500/dbfg/parallel/get/" + modelId;

                                        that.$axios.get(url).then(res => {
                                            if (res.code === 200) {
                                                let nodeId = paramBtnId.substr(0, paramBtnId.length - 6);
                                                let nodeInfo = mynodes.filter(e => e.id === nodeId)[0];
                                                let paramsFormat = JSON.parse(res.body.parameters);
                                                // that.$Bus.$emit('showParamInputDialog', nodeInfo, paramsFormat);


                                                //判断某个节点有无上游节点
                                                let conn_list = that.jsPlumbInstance.getAllConnections();
                                                let sourceNodes = [];
                                                let targetNodes = [];
                                                let allNodes = [];
                                                if (conn_list.length > 0) {
                                                    for (let i = 0; i < conn_list.length; i++) {
                                                        let source_id = conn_list[i]["sourceId"];
                                                        let target_id = conn_list[i]["targetId"];
                                                        let data = {
                                                            "source": source_id,
                                                            "target": target_id
                                                        }
                                                        allNodes.push(data);
                                                        sourceNodes.push(source_id);
                                                        targetNodes.push(target_id);
                                                    }
                                                    if (targetNodes.indexOf(nodeId) > -1) {
                                                        // alert("有上游节点")
                                                        let upNodes = [];
                                                        //获得上游节点信息
                                                        for (let item of allNodes) {
                                                            if (item.target == nodeId) {
                                                                for (let role of that.modelsInFlow) {
                                                                    if (role.id == item.source) {
                                                                        let data = {
                                                                            "params": role.param,
                                                                            "nodeId": item.source
                                                                        }
                                                                        upNodes.push(data);
                                                                    }
                                                                }

                                                            }
                                                        }
                                                        //上游节点参数信息
                                                        let data = {
                                                            "nodeInfo": nodeInfo,
                                                            "paramsFormat": paramsFormat,
                                                            "upnode": "1",
                                                            "upnodes": upNodes
                                                        }
                                                        that.$Bus.$emit('showParamInputDialog', data);
                                                    } else {
                                                        // alert("没有上游节点")
                                                        let data = {
                                                            "nodeInfo": nodeInfo,
                                                            "paramsFormat": paramsFormat,
                                                            "upnode": "0",
                                                            "upnodes": []
                                                        }
                                                        that.$Bus.$emit('showParamInputDialog', data);
                                                        // that.$Bus.$emit('showParamInputDialog', nodeInfo, paramsFormat);
                                                    }
                                                } else {
                                                    // alert("没有上游节点")
                                                    let data = {
                                                        "nodeInfo": nodeInfo,
                                                        "paramsFormat": paramsFormat,
                                                        "upnode": "0",
                                                        "upnodes": []
                                                    }
                                                    that.$Bus.$emit('showParamInputDialog', data);

                                                }


                                            } else {
                                                that.$message({
                                                    type: 'warning',
                                                    message: res.message
                                                })
                                            }
                                        }).catch(function (error) {
                                            console.log(error);
                                            that.$message.error('模型信息获取失败！')
                                        });
                                    };
                                }


                                that.jsPlumbInstance.draggable(val['id'], {
                                    grid: [1, 1],
                                    containment: "workFlowContainer"
                                });
                                let deleteNodeid = paramBtnId.substr(0, paramBtnId.length - 6);
                                let currentNode = document.getElementById(deleteNodeid);
                                // //双击删除自己，以及与自身相关的连线。
                                currentNode.ondblclick = function () {
                                    that.jsPlumbInstance.remove(deleteNodeid);
                                };

                                that.jsPlumbInstance.addEndpoint(val['id'], {
                                    anchor: "Right",
                                    maxConnections: -1,
                                    endpointStyle: {
                                        fill: "rgb(33, 194, 33)"
                                    },
                                    isSource: true
                                });
                                that.jsPlumbInstance.addEndpoint(val['id'], {
                                    anchor: "Left",
                                    maxConnections: -1,
                                    endpointStyle: {
                                        fill: "#346789"
                                    },
                                    isTarget: true
                                });

                                // drop_function(event, ui);
                            });
                        })


                        //画线
                        jQuery.each(nets_conn, function (id, val) {
                            that.jsPlumbInstance.ready(function () {
                                that.jsPlumbInstance.connect({
                                    "source": val['source']['id'],
                                    "target": val['target']['id'],
                                    "anchors": [val['source']['anchor_position'], val['target']['anchor_position']],
                                    "DragOptions": {cursor: "pointer", zIndex: 2000},
                                    "endpoint": ["Dot", {radius: 5}],
                                    "paintStyle": {stroke: "#346789", strokeWidth: 1},
                                    "maxConnections": -1,
                                    "connector": ["Bezier", {curviness: 70}],
                                    "overlays": [["Arrow", {width: 10, length: 10, location: 1}]],
                                    "connectionsDetachable": true,
                                    // "connectionsDetachable": true,
                                })
                            });
                        });


                    }
                }).catch(function (error) {

                })


            },
            getNewWorkFlowId(id) {
                this.currentWorkflowId = id;
                this.getWorkflow();
            },
            saveFlow() {
                //保存线的样式
                let conn_list = this.jsPlumbInstance.getAllConnections();
                let connections = [];
                let connectionsStyle = [];
                let nodes = [];
                let nodesStyle = [];
                //保存连线样式
                for (let i = 0; i < conn_list.length; i++) {
                    let source_id = conn_list[i]["sourceId"];
                    let target_id = conn_list[i]["targetId"];
                    let conn = {
                        "source": {
                            "id": source_id,
                            "anchor_position": conn_list[i]["endpoints"][0]["anchor"]["type"]
                        },
                        "target": {
                            "id": target_id,
                            "anchor_position": conn_list[i]["endpoints"][1]["anchor"]["type"]
                        }
                    };
                    let data = {
                        "source": source_id,
                        "target": target_id,
                    };
                    connections.push(data);
                    connectionsStyle.push(conn);
                }
                //保存节点样式
                $("#workFlowContainer").find(".modelNode").each(function (index, element) {
                    let id = $(element).attr('id');
                    let text = $(element).text();
                    let net = {
                        // "name": $(element).attr('name'),
                        // "attribute": eval('(' + window.localStorage.getItem(id) + ')'),
                        "id": id,
                        "name": text,
                        // "modelId":id.substring(0, id.indexOf("_")),
                        // "nodeInfo":that.modelsInFlow[nodeNum],
                        "left": $(element).css('left'),
                        "top": $(element).css('top')
                    }
                    nodesStyle.push(net);
                    // nodeNum++;
                    let modeItem = {
                        "id": id,
                        "name": id.substring(0, id.indexOf("_")) + "Task",
                        "modelId": id.substring(0, id.indexOf("_")),
                        "param": []
                    };
                    nodes.push(modeItem);
                });
                let style = {
                    "net": nodesStyle,
                    "connections": connectionsStyle
                };
                let param = {
                    "style": JSON.stringify(style),
                    "connections": connections,
                    "nodes": this.modelsInFlow,
                    "id": this.currentWorkflowId
                };
                if (this.currentWorkflowId !== "") {
                    this.$confirm('请选择更新加载工作流或另存为新的工作流', '提示', {
                        confirmButtonText: '更新',
                        cancelButtonText: '另存为',
                        type: 'warning'
                    }).then(() => {
                        alert("更新工作流")
                        let url = "http://192.168.1.5:9500/dbfg/workflow/dags/save";
                        let that = this;
                        this.$axios.post(url, param)
                            .then(function (res) {
                                if (res.code == 200) {
                                    that.$message({
                                        message: res.message,
                                        type: 'success'
                                    });
                                } else {
                                    that.$message({
                                        message: res.message,
                                        type: 'warning'
                                    });
                                }
                            }).catch(function (error) {
                            console.log(error)
                        })
                    }).catch(() => {
                        alert("另存工作流")
                        this.$Bus.$emit("saveWorkflow", param);
                    });

                } else {
                    this.$Bus.$emit("saveWorkflow", param);
                }

                this.getWorkflow();
            },
            runFlow() {
                if (this.wuhuan()) {
                    if (this.validateDAG()) {
                        this.$Bus.$emit("newWorkflowDialog", true);
                    }
                } else {
                    this.$message.error('图中有环，请修改！')
                }

            },
            cleanFlow() {
                // this.jsPlumbInstance.empty();
                // $("#workFlowContainer").empty();
                // $('#workFlowContainer').html('')
                this.modelsInFlow = [];
                let nodes = document.getElementById("workFlowContainer").children;
                let nodesId = [];
                for (let i = 0; i < nodes.length; i++) {
                    nodesId.push(nodes[i].id);
                }
                for (let i = 0; i < nodesId.length; i++) {
                    this.jsPlumbInstance.remove(nodesId[i]);
                }
            },
            getModel() {
                let that = this;
                let url = this.$URL.parallelListUrl + this.pageSize + '&pageNo=' + this.pageNo;
                this.$axios.get(url).then(res => {
                    if (res.code === 200) {
                        that.models = res.body.result;
                    } else {
                        that.$message({
                            type: 'warning',
                            message: res.message
                        })
                    }
                }).catch(function (error) {
                    console.log(error);
                    that.$message.error('模型列表获取失败！')
                })
            },
            initJsPlumb() {
                // if (!this.innited) {

                let that = this;
                jsPlumb.ready(function () {
                    let jsPlumbInstance = jsPlumb.getInstance({
                        // Id: 'jsInstance',
                        DragOptions: {cursor: "pointer", zIndex: 2000},
                        PaintStyle: {stroke: "#346789", strokeWidth: 1},
                        Endpoinet: ["Dot", {radius: 5}],
                        Connector: ["Bezier", {curviness: 70}],
                        ConnectionOverlays: [
                            ["Arrow",
                                {
                                    location: 1,
                                    visible: true,
                                    width: 11,
                                    height: 11,
                                    id: "Arrow"
                                }
                            ],
                            ["Label",
                                {
                                    location: 0.1,
                                    id: "Label",
                                    cssClass: "arrow-label",
                                    events: {
                                        tap() {
                                            console.log("Label");
                                        }
                                    }
                                }]
                        ],
                        // Container: "workFlowContainer"
                    });
                    // 有东西拖到#workFlowContainer时，执行drop函数，workFlowContainer容纳可拖动元素；
                    $("#workFlowContainer").droppable({
                        scope: "nodes",
                        drop: function (ev, ui) {
                            if (document.getElementById("workFlowContainer").children.length === 0) {
                                // that.modelNodesNumb = 0;
                            }
                            if (document.getElementById("workFlowContainer").children.length === 0) {
                                that.currentWorkflowId = "";
                            }
                            let modelId = ui.helper.attr("tag");
                            // let nodeId = modelId + "_" + that.modelNodesNumb;
                            let nodeId = modelId + "_" + MathRand();
                            let paramBtnId = nodeId + "_param";
                            let nodeHtml = '';
                            // nodeHtml = `<div id="${nodeId}" class="modelNode"><span>${that.modelNodesNumb + ":" + ui.helper.text()}<i class="fa fa-wpforms" id="${paramBtnId}"></i></span></div>`;
                            nodeHtml = `<div id="${nodeId}" class="modelNode"><span>${ui.helper.text()}<i class="fa fa-wpforms" id="${paramBtnId}"></i></span></div>`;
                            $(this).append(nodeHtml);
                            //记录当前正在使用的模型
                            let currentNode = document.getElementById(nodeId);
                            let modeItem = {
                                "id": nodeId,
                                "name": modelId + "Task",
                                "modelId": modelId,
                                "param": []
                            };
                            //每个节点
                            //输入输出  数量限制参数
                            let inCount = 0;
                            let outCount = 0;
                            let url = that.$URL.parallelDetailUrl + modelId;
                            that.$axios.get(url).then(res => {
                                if (res.code === 200) {
                                    let paramsFormat = JSON.parse(res.body.parameters);
                                    if (paramsFormat.length != 0) {
                                        for (let item of paramsFormat) {
                                            if (parseInt(item.in) > -1) {
                                                inCount++;
                                            }
                                            if (parseInt(item.out) > -1) {
                                                outCount++
                                            }
                                        }
                                    }
                                    jsPlumbInstance.addEndpoint(nodeId, {
                                        anchor: "Right",
                                        maxConnections: outCount,
                                        endpointStyle: {
                                            fill: "rgb(33, 194, 33)"
                                        },
                                        isSource: true
                                    });
                                    jsPlumbInstance.addEndpoint(nodeId, {
                                        anchor: "Left",
                                        maxConnections: inCount,
                                        endpointStyle: {
                                            fill: "#346789"
                                        },
                                        isTarget: true
                                    });

                                } else {
                                    that.$message({
                                        type: 'warning',
                                        message: res.message
                                    })
                                }
                            }).catch(function (error) {
                                console.log(error);
                                that.$message.error('模型信息获取失败！')
                            });

                            that.modelsInFlow.push(modeItem);
                            // that.modelNodesNumb++;
                            // console.log("add");
                            // console.log(that.modelsInFlow);

                            let newTop = ui.position.top - $("#workFlowContainer").position().top;
                            let newLeft = ui.position.left - $("#workFlowContainer").position().left;
                            $("#" + nodeId).css({
                                top: newTop + "px",
                                left: newLeft + "px"
                            });
                            //dialog填写参数
                            if (document.getElementById(paramBtnId)) {
                                document.getElementById(paramBtnId).onclick = function () {
                                    let url = that.$URL.parallelDetailUrl + modelId;
                                    that.$axios.get(url).then(res => {
                                        if (res.code === 200) {
                                            //paramBtnId = 节点的id + '_param'
                                            let nodeId = paramBtnId.substr(0, paramBtnId.length - 6);
                                            let nodeInfo = that.modelsInFlow.filter(e => e.id === nodeId)[0];
                                            let paramsFormat = JSON.parse(res.body.parameters);

                                            //判断某个节点有无上游节点
                                            let conn_list = that.jsPlumbInstance.getAllConnections();
                                            let sourceNodes = [];
                                            let targetNodes = [];
                                            let allNodes = [];
                                            if (conn_list.length > 0) {
                                                for (let i = 0; i < conn_list.length; i++) {
                                                    let source_id = conn_list[i]["sourceId"];
                                                    let target_id = conn_list[i]["targetId"];
                                                    let data = {
                                                        "source": source_id,
                                                        "target": target_id
                                                    }
                                                    allNodes.push(data);
                                                    sourceNodes.push(source_id);
                                                    targetNodes.push(target_id);
                                                }
                                                if (targetNodes.indexOf(nodeId) > -1) {
                                                    // alert("有上游节点")
                                                    let upNodes = [];
                                                    //获得上游节点信息
                                                    for (let item of allNodes) {
                                                        if (item.target == nodeId) {
                                                            for (let role of that.modelsInFlow) {
                                                                if (role.id == item.source) {
                                                                    let data = {
                                                                        "params": role.param,
                                                                        "nodeId": item.source
                                                                    }
                                                                    upNodes.push(data);
                                                                }
                                                            }

                                                        }
                                                    }
                                                    //上游节点参数信息？？


                                                    let data = {
                                                        "nodeInfo": nodeInfo,
                                                        "paramsFormat": paramsFormat,
                                                        "upnode": "1",
                                                        "upnodes": upNodes
                                                    }
                                                    that.$Bus.$emit('showParamInputDialog', data);
                                                } else {
                                                    // alert("没有上游节点")
                                                    let data = {
                                                        "nodeInfo": nodeInfo,
                                                        "paramsFormat": paramsFormat,
                                                        "upnode": "0",
                                                        "upnodes": []
                                                    }
                                                    that.$Bus.$emit('showParamInputDialog', data);
                                                    // that.$Bus.$emit('showParamInputDialog', nodeInfo, paramsFormat);
                                                }
                                            } else {
                                                // alert("没有上游节点")
                                                let data = {
                                                    "nodeInfo": nodeInfo,
                                                    "paramsFormat": paramsFormat,
                                                    "upnode": "0",
                                                    "upnodes": []
                                                }
                                                that.$Bus.$emit('showParamInputDialog', data);


                                            }

                                            // that.$Bus.$emit('showParamInputDialog', nodeInfo, paramsFormat);
                                        } else {
                                            that.$message({
                                                type: 'warning',
                                                message: res.message
                                            })
                                        }
                                    }).catch(function (error) {
                                        console.log(error);
                                        that.$message.error('模型信息获取失败！')
                                    });
                                };
                            }

                            //双击删除自己，以及与自身相关的连线。
                            currentNode.ondblclick = function () {
                                for (let i = 0; i < that.modelsInFlow.length; i++) {
                                    if (that.modelsInFlow[i].id === nodeId) {
                                        that.modelsInFlow.splice(i, 1);
                                        break;
                                    }
                                }
                                // that.modelNodesNumb--;
                                // console.log("rm");
                                // console.log(that.modelsInFlow);
                                jsPlumbInstance.remove(nodeId);
                            };

                            //设置节点可拖动
                            jsPlumbInstance.draggable(nodeId, {
                                grid: [1, 1],
                                containment: "workFlowContainer"
                            });


                        }
                    });
                    //左侧栏模型可拖动
                    document.onmousedown = function () {
                        $(".modelsContainer").css("overflow-y", "hidden");
                    };
                    document.onmouseup = function () {
                        $(".modelsContainer").css("overflow-y", "auto");
                    };
                    $(".el-card").draggable({
                        scope: "nodes",
                        helper: function () {
                            let _id = $(this).attr('id');
                            let _html = $(this).html();
                            let clone = $('<div tag="' + _id + '" class="row-clone">' + _html + '</div>');
                            clone.appendTo('body');
                            return clone;
                        },
                        containment: 'body',
                        appendTo: 'body'
                    });
                    jsPlumb.fire("jsPlumbDemoLoaded", jsPlumbInstance);
                    that.jsPlumbInstance = jsPlumbInstance;
                });
                // }
            },
            validateDAG() {
                //检查参数是否完整
                for (let i = 0; i < this.modelsInFlow.length; i++) {
                    if (this.modelsInFlow[i].param.length === 0) {
                        this.$message.error(this.modelsInFlow[i].id + ": 参数未填写完整.");
                        return false;
                    } else {
                        if (this.modelsInFlow[i].param.filter(e => e.val === null || e.val.trim().length === 0).length > 0) {
                            this.$message.error(this.modelsInFlow[i].id + ": 参数未填写完整.");
                            return false;
                        }
                    }
                }
                //TODO 有向无环图验证 游离节点验证
                return true;
            },
            getWorkflow() {
                let url = "http://192.168.1.5:9500/dbfg/workflow/dags/all?pageNo=" + this.pageNo1 + "&pageSize=" + this.pageSize1;
                this.$axios.get(url).then(res => {
                    if (res.code == 200) {
                        this.workflows = res.body.result;
                        this.totalCount1 = res.body.totalCount;
                    }
                }).catch(function (error) {

                })
            }
        },
        created() {
            // alert("created");
            let that = this;
            this.getModel();
            this.getWorkflow();
            this.$Bus.$off('newWorkflowName');
            this.$Bus.$on("newWorkflowName", res => {
                that.loading = true;
                let url = "http://192.168.1.5:9500/dbfg/workflow/tasks/submit";
                let lineList = that.jsPlumbInstance.getAllConnections();
                let methodUseId = [];
                let connections = [];
                for (let listItem of lineList) {
                    let sourceId = listItem.source.id;
                    let targetId = listItem.target.id;
                    let data = {
                        "source": listItem.source.id,
                        "target": listItem.target.id
                    }
                    connections.push(data);
                    methodUseId.push(sourceId + "#" + targetId);
                }
                // alert(JSON.stringify(methodUseId));
                // alert(JSON.stringify(this.modelsInFlow));
                let params = {
                    // "id": res + Math.random().toString(),
                    "id": generateUUID(),
                    "name": res.fileName,
                    "description": res.fileDescription,
                    "connections": connections,
                    "nodes": that.modelsInFlow,
                    // "createdtime": that.param.createdtime,
                    // "lastmodifytime": that.param.lastmodifytime
                }
                that.$axios.post(url, params)
                    .then(function (res) {
                        if (res.code == 200) {
                            that.loading = false;
                            that.$message({
                                message: res.message + "请到任务管理界面查看运行进度",
                                type: 'success'
                            });

                        } else {
                            that.loading = false;
                            that.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
                    }).catch(function (error) {
                    that.loading = false;
                    console.log(error)
                })
            })
        },
        beforeUpdate() {
            alert("update");
            // if (this.jsPlumbInstance.version === undefined)
            if (this.innited <3) {
                //整个页面刷新后进入只初始化一次即可，从别的页面跳转过来需要初始化两次,如果在别的页面有过刷新操作和刚刚npm需要三次
                this.initJsPlumb();
                this.innited++;
            }
        },
        mounted() {
            // alert("mounted")
            // this.initJsPlumb();
        },

    };

</script>
<style>
    .model {
        height: 40px;
        background: #7cc576;
        font-size: 25px;
        margin-bottom: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .row-clone {
        width: auto;
        height: 35px;
        line-height: 35px;
        text-align: center;
        background-color: #eeeeef;
        border-radius: 0.5em;
        opacity: 0.8;
        padding: 0 25px;
        font-size: 11px;
    }

    #workFlowContainer {
        width: 98%;
        height: 98%;
        float: left;
        margin-left: 1%;
        margin-top: 0.5%;
        /*top: 20px;*/
        position: relative;
        /*margin-left: 20px;*/
        /*border: 2px solid black;*/
        /*box-shadow: darkgrey 0px 0px 30px 5px*/
        border-radius: 4px;
        border: 1px solid #163308;
        box-shadow: inset 0 0 5px 5px #ccc;
    }

    .modelNode {
        box-shadow: 2px 2px 19px #aaa;
        -o-box-shadow: 2px 2px 19px #aaa;
        -webkit-box-shadow: 2px 2px 19px #aaa;
        -moz-box-shadow: 2px 2px 19px #aaa;
        -moz-border-radius: 50%;
        border-radius: 50%;
        opacity: 0.8;
        filter: alpha(opacity=80);
        border: 1px solid #346789;
        background-color: #eeeeef;
        color: black;
        font-size: 9pt;
        cursor: pointer;
        width: auto;
        height: auto;
        position: absolute;
    }

    .modelNode span {
        display: inline-block;
        text-align: center;
        padding: 15px;
    }

    .modelNode span i {
        padding-left: 6px;
    }

</style>